package com.kcwx.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.kcwx.common.core.domain.TreeSelect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import com.kcwx.common.annotation.Log;
import com.kcwx.common.constant.UserConstants;
import com.kcwx.common.core.controller.BaseController;
import com.kcwx.common.core.domain.AjaxResult;
import com.kcwx.common.core.domain.entity.SysDept;
import com.kcwx.common.core.domain.entity.SysRole;
import com.kcwx.common.core.domain.entity.SysUser;
import com.kcwx.common.core.domain.model.LoginUser;
import com.kcwx.common.core.page.TableDataInfo;
import com.kcwx.common.enums.BusinessType;
import com.kcwx.common.utils.StringUtils;
import com.kcwx.common.utils.poi.ExcelUtil;
import com.kcwx.common.core.domain.AdminValid;

import com.kcwx.framework.web.service.SysPermissionService;
import com.kcwx.framework.web.service.TokenService;

import com.kcwx.shareddomain.common.dto.DeleteDto;
import com.kcwx.shareddomain.common.dto.DelParaValid;
import com.kcwx.shareddomain.system.query.SysUserQuery;
import com.kcwx.shareddomain.system.query.SysDeptQuery;
import com.kcwx.shareddomain.system.query.SysRoleQuery;
import com.kcwx.shareddomain.system.dto.SysRoleEditDto;
import com.kcwx.shareddomain.system.dto.RoleAuthUserDto;

import com.kcwx.system.dtomap.SysRoleMap;
import com.kcwx.system.domain.SysUserRole;
import com.kcwx.system.service.ISysDeptService;
import com.kcwx.system.service.ISysRoleService;
import com.kcwx.system.service.ISysUserService;

/**
 * 角色信息
 * 
 */
@Api(tags = "系统管理-角色管理")
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController
{
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private SysRoleMap sysRoleMap;

    /**
     * 新增角色
     */
    @ApiOperation("新增")
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "新增角色", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody SysRoleEditDto dto)
    {
        SysRole role=sysRoleMap.AddDtoToEntity(dto);
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(getUsername());
        int rowsAffect = roleService.insertRole(role);
        return rowsAffect>0?success():error("新增失败");
    }

    /**
     * 修改角色
     */
    @ApiOperation("修改")
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "修改角色", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody SysRoleEditDto dto)
    {
        SysRole role=sysRoleMap.EditDtoToEntity(dto);
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getId());
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(getUsername());

        if (roleService.updateRole(role) > 0)
        {
            // 更新缓存用户权限
            LoginUser loginUser = getLoginUser();
            if (StringUtils.isNotNull(loginUser.getUser()) && !AdminValid.userIsAdmin(loginUser.getUser().getId()))
            {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return success();
        }
        return error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 删除角色
     */
    @ApiOperation("删除角色")
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "删除角色", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove")
    public AjaxResult remove(@RequestBody DeleteDto dto)
    {
        Long id=DelParaValid.validDel(dto);
        int rowsAffect=roleService.deleteRoleById(id,getUsername());
        return rowsAffect>0?success():error("删除失败");
    }
    /**
     * 批量删除角色
     */
    @ApiOperation("批量删除角色")
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "批量删除角色", businessType = BusinessType.DELETE)
    @DeleteMapping("/batchRemove")
    public AjaxResult batchRemove(@RequestBody DeleteDto dto)
    {
        Long []ids=DelParaValid.validBatchDel(dto);
        int rowsAffect=roleService.deleteRoleByIds(ids,getUsername());
        return rowsAffect>0?success():error("删除失败");
    }
    /**
     * 分页查询
     */
    @ApiOperation("分页查询")
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @Log(title = "角色分页查询", businessType = BusinessType.OTHER)
    @PostMapping("/list")
    public AjaxResult list(@RequestBody SysRoleQuery role)
    {
        startPage();
        List<SysRole> list = roleService.selectRoleList(role);
        return success(getDataTable(list));
    }

    /**
     * 根据id获取详细信息
     */
    @ApiOperation("根据id获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @Log(title = "根据id获取角色", businessType = BusinessType.OTHER)
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable Long roleId)
    {
        roleService.checkRoleDataScope(roleId);
        return success(roleService.selectRoleById(roleId));
    }
    /**
     * 修改保存数据权限
     */
    @ApiOperation("修改保存数据权限")
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "修改保存角色数据权限", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody SysRoleEditDto dto)
    {
        SysRole role=sysRoleMap.EditDtoToEntity(dto);
        role.setUpdateBy(getUsername());
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getId());
        int rowsAffect=roleService.authDataScope(role);
        return rowsAffect>0?success():error("操作失败");
    }

    /**
     * 状态修改
     */
    @ApiOperation("修改角色状态")
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "修改角色状态", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysRoleEditDto dto)
    {
        SysRole role=sysRoleMap.EditDtoToEntity(dto);
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getId());
        role.setUpdateBy(getUsername());
        int rowsAffect=roleService.updateRoleStatus(role);
        return rowsAffect>0?success():error("状态修改失败");
    }

    /**
     * 获取角色选择框列表
     */
    @ApiOperation("获取角色选择框列表")
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @Log(title = "获取角色选择框列表", businessType = BusinessType.OTHER)
    @GetMapping("/optionselect")
    public AjaxResult optionselect()
    {
        List<SysRole> roleList=roleService.selectRoleAll();
        if(!roleList.isEmpty()){
            roleList=roleList.stream().filter(role->role.getStatus()==1&&!AdminValid.roleIsAdmin(role.getId())).collect(Collectors.toList());
        }
        return success(roleList);
    }

    /**
     * 查询已分配角色用户分页列表
     */
    @ApiOperation("查询已分配角色用户分页列表")
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @Log(title = "查询已分配角色用户分页列表", businessType = BusinessType.OTHER)
    @PostMapping("/authUser/allocatedList")
    public AjaxResult allocatedList(@RequestBody SysUserQuery user)
    {
        startPage();
        List<SysUser> list = userService.selectAllocatedList(user);
        return success(getDataTable(list));
    }

    /**
     * 查询未分配角色用户列表
     */
    @ApiOperation("查询未分配角色用户列表")
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @Log(title = "查询未分配角色用户列表", businessType = BusinessType.OTHER)
    @PostMapping("/authUser/unallocatedList")
    public AjaxResult unallocatedList(@RequestBody SysUserQuery user)
    {
        startPage();
        List<SysUser> list = userService.selectUnallocatedList(user);
        return success(getDataTable(list));
    }

    /**
     * 取消授权用户
     */
    @ApiOperation("取消授权用户")
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "取消授权用户", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public AjaxResult cancelAuthUser(@RequestBody SysUserRole userRole)
    {
        int rowsAffect=roleService.deleteAuthUser(userRole);
        return rowsAffect>0?success():error("操作失败");
    }

    /**
     * 批量取消授权用户
     */
    @ApiOperation("批量取消授权用户")
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "批量取消授权用户", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    public AjaxResult cancelAuthUserAll(@RequestBody RoleAuthUserDto dto)
    {
        int rowsAffect=roleService.deleteAuthUsers(dto.getRoleId(), dto.getUserIds());
        return rowsAffect>0?success():error("操作失败");
    }

    /**
     * 批量选择用户授权
     */
    @ApiOperation("批量选择用户授权")
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "批量选择用户授权", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    public AjaxResult selectAuthUserAll(@RequestBody RoleAuthUserDto dto)
    {
        roleService.checkRoleDataScope(dto.getRoleId());
        int rowsAffect=roleService.insertAuthUsers(dto.getRoleId(), dto.getUserIds());
        return rowsAffect>0?success():error("操作失败");
    }

    /**
     * 获取对应角色部门树列表
     */
    @ApiOperation("获取对应角色部门树列表")
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @Log(title = "获取对应角色部门树列表", businessType = BusinessType.OTHER)
    @GetMapping(value = "/deptTree")
    public AjaxResult deptTree(Long roleId)
    {
        List<Long> checkedKeys=deptService.selectDeptListByRoleId(roleId);
        SysDeptQuery deptQuery=new SysDeptQuery();
        deptQuery.setStatus(1);
        List<TreeSelect>deptList=deptService.selectDeptTreeList(deptQuery);
        //管理员自定义权限默认全部
        if(AdminValid.roleIsAdmin(roleId)){
           List<SysDept> deptData=deptService.selectDeptList(deptQuery);
           checkedKeys=deptData.stream().map(SysDept::getId).collect(Collectors.toList());
        }
        Map<String,Object> dataInfo=new HashMap<String,Object>();
        dataInfo.put("checkedKeys",checkedKeys);
        dataInfo.put("depts",deptList);
        return success(dataInfo);
    }
}
